<template>
  <div class="w-full h-full mt-10">
    <vue-ueditor-wrap
      v-model="content"
      :editor-id="id"
      :editorDependencies="['ueditor.config.js', 'ueditor.all.js']"
      :config="editorConfig"
      style="width: 600px; height: auto"
      @beforeInit="addCustomButtom"
    ></vue-ueditor-wrap>
    <a-modal width="700px" v-model:visible="imgvisible" @ok="handleOkimg" title="插入图片">
      <a-form auto-label-width size="small" :model="form" class="form my-10">
        <a-form-item label="上传图片">
          <MsUpload v-model="imgUrl" placeholder="点击上传或直接在下方输入框输入链接"></MsUpload>
        </a-form-item>
        <a-form-item label="图片链接">
          <a-input v-model="imgUrl" placeholder="输入链接或在上方点击上传"></a-input>
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal width="700px" v-model:visible="videovisible" @ok="handleOkvideo" title="插入视频">
      <a-form auto-label-width size="small" :model="form" class="form my-10">
        <a-form-item label="上传视频">
          <MsUpload v-model="videoUrl" type="video" placeholder="点击上传或直接在下方输入框输入链接"></MsUpload>
        </a-form-item>
        <a-form-item label="视频链接">
          <a-input v-model="videoUrl" placeholder="输入链接或在上方点击上传"></a-input>
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal v-model:visible="visible" @before-ok="onOk" draggable width="1200px">
      <template #title>
        <a-radio-group v-model="type" type="button">
          <a-radio value="goods">插入商品</a-radio>
          <a-radio value="coupon">插入券/会场</a-radio>
        </a-radio-group>
      </template>
      <template v-if="type === 'goods'">
        <div>
          <a-form :model="goodsForm" layout="inline" size="small" auto-label-width>
            <a-form-item hide-label field="goodsStyle">
              <a-select placeholder="选择商品模板" v-model="goodsForm.goodsStyle" class="w-34n" allow-clear>
                <a-option v-for="(item, index) in bestMaterialTemplate" :key="item.value" :value="item.content">
                  <a-popover position="right">
                    <p>{{ item.label }}</p>
                    <template #content>
                      <img :src="thumbnail[index]" class="w-50n" style="object-fit: contain" />
                    </template>
                  </a-popover>
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item field="sourceType" hide-label v-if="goodsForm.goodsStyle">
              <a-select v-model="goodsForm.sourceType" placeholder="选择商品平台" class="w-34n" allow-clear>
                <a-option v-for="item in platformList" :key="item.id" :value="item.id" :label="item.title"></a-option>
              </a-select>
            </a-form-item>
            <a-form-item field="goodsId" hide-label v-if="goodsForm.sourceType">
              <a-input v-model="goodsForm.goodsId" placeholder="请输入商品ID" allow-clear />
            </a-form-item>
            <a-form-item field="activityId" hide-label v-if="goodsForm.sourceType">
              <a-input v-model="goodsForm.activityId" placeholder="请输入券ID" allow-clear />
            </a-form-item>
            <a-form-item hide-label v-if="goodsForm.sourceType">
              <a-button :loading="getGoodsLoading" type="primary" @click="getGoods">
                <template #icon> <icon-find-replace /></template>
                获取商品
              </a-button>
              <a-upload
                class="ml-10"
                name="file"
                :show-file-list="false"
                :headers="{ Authorization: token }"
                :custom-request="onImportGoods"
              >
                <template #upload-button>
                  <a-button type="primary" size="small" :loading="importLoading">
                    <template #icon><icon-to-bottom /></template>
                    <span>导入</span>
                  </a-button>
                </template>
              </a-upload>
            </a-form-item>
          </a-form>
          <a-table :columns="columns" :data="tableData" class="mt-10" :pagination="false" :scroll="{ y: 500 }">
            <template #picUrl="{ record }">
              <ImgHoverPreview :width="50" :url="record.picUrl" />
            </template>
            <template #action="{ rowIndex }">
              <a-button type="text" size="small" @click="openSetGoods(rowIndex)"> 设置 </a-button>
              <a-popconfirm content="是否确认删除?" @ok="onDeleteItem(rowIndex)">
                <a-button type="text" size="small"> 删除 </a-button>
              </a-popconfirm>
            </template>
          </a-table>
        </div>
      </template>
      <template v-else>
        <a-form :model="couponForm" size="small" auto-label-width>
          <a-form-item field="sourceType" label="所属平台">
            <a-select v-model="couponForm.sourceType" placeholder="选择券/会场/商品所属平台" allow-clear>
              <a-option v-for="item in platformList" :key="item.id" :value="item.id" :label="item.title"></a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="背景图" field="goodsCouponBg">
            <MsUpload v-model="couponForm.goodsCouponBg"></MsUpload>
          </a-form-item>
          <a-form-item field="opentype" label="打开方式">
            <a-select placeholder="选择打开方式" v-model="couponForm.opentype" allow-clear>
              <a-option v-for="item in openArr" :key="item.id" :value="item.id">
                {{ item.title }}
              </a-option>
            </a-select>
          </a-form-item>
          <template v-if="couponForm.opentype === 1">
            <a-form-item field="itemsourceid" label="商品ID">
              <a-input v-model="couponForm.itemsourceid" placeholder="请输入商品ID" allow-clear />
            </a-form-item>
          </template>
          <template v-else>
            <a-form-item
              field="url"
              :label="couponForm.opentype === 2 ? 'H5链接' : couponForm.opentype === 3 ? '会场ID/链接' : ''"
            >
              <a-input
                v-model="couponForm.url"
                :placeholder="`请输入${
                  couponForm.opentype === 2 ? 'H5链接' : couponForm.opentype === 3 ? '会场ID/链接' : ''
                }`"
                allow-clear
              />
            </a-form-item>
          </template>
          <template v-if="couponForm.opentype === 3 || couponForm.opentype === 4">
            <a-form-item field="isturning" label="是否需要转链">
              <a-space>
                <a-radio-group v-model="couponForm.isturning">
                  <a-radio :value="1">需要</a-radio>
                  <a-radio :value="0">不需要</a-radio>
                </a-radio-group>
                <span class="font-bold text666 mb-4">(社群中的链接请勾选不需要)</span>
              </a-space>
            </a-form-item>
          </template>
        </a-form>
      </template>
    </a-modal>
    <a-modal v-model:visible="setGoodsVisible" title="商品设置" @ok="setGoods" draggable>
      <a-form size="small" auto-label-width :model="setGoodsForm">
        <a-form-item field="goodsCouponDesc" label="券描述">
          <a-input v-model="setGoodsForm.goodsCouponDesc" placeholder="请输入券描述" allow-clear />
        </a-form-item>
        <a-form-item field="goodsDesc" label="商品推荐语">
          <a-input v-model="setGoodsForm.goodsDesc" placeholder="请输入推荐语" allow-clear />
        </a-form-item>
        <a-form-item field="opentype" label="打开方式">
          <a-select placeholder="选择打开方式" v-model="setGoodsForm.opentype" allow-clear>
            <a-option v-for="item in openArr" :key="item.id" :value="item.id">
              {{ item.title }}
            </a-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { usePlatform } from '@/hooks/app'
import { Notification } from '@arco-design/web-vue'
import { deleteEmpty } from '@/utils/common'
import { bestMaterialTemplateTree, goodsDetail2, bestMaterialImportForList } from '@/apis'
import { getToken } from '@/utils/auth'
const emit = defineEmits(['input'])

const props = defineProps(['modelValue', 'height'])
const form = reactive({})
const id = Math.random().toString(36).substring(2, 15) + '-ueditor-' + +new Date()
const importLoading = ref(false)
const content = ref('')
const editorConfig = reactive({
  UEDITOR_HOME_URL: '/UEditor/',
  autoHeightEnabled: false,
  initialFrameHeight: 600
})

// 上传组件需要增加token
const tokenSource = getToken()
const token = tokenSource ? `'Bearer ${tokenSource}'` : ''
const setHeightFun = (height) => {
  setTimeout(() => {
    const myEditor = window.UE.getEditor(id)
    myEditor?.setHeight(height) //设置高度
  }, 500)
}
//插入图片
const imgvisible = ref(false)
const imgUrl = ref()
const handleOkimg = async () => {
  const myEditor = window.UE.getEditor(id)
  const image = `<img style="max-width:100%;" src="${imgUrl.value}" />`
  myEditor.execCommand('inserthtml', image)
  imgUrl.value = ''
}
//插入视频
const videovisible = ref(false)
const videoUrl = ref()
const handleOkvideo = async () => {
  const myEditor = window.UE.getEditor(id)
  const video = `<br/><br/><video controls width="100%" autoplay loop><source src="${videoUrl.value}" type="video/mp4" /></video><br/><br/><br/>`
  myEditor.execCommand('inserthtml', video)
  videoUrl.value = ''
}
const visible = ref(false)
const type = ref('goods')
const bestMaterialTemplate = ref([])
const thumbnail = [
  'https://images.maishou88.com/admin/topic_background_image/20220617/20220617180251_1990.jpg',
  'https://images.maishou88.com/admin/topic_background_image/20220617/20220617180049_6965.jpg',
  'https://images.maishou88.com/admin/topic_background_image/20220617/20220617180156_2444.jpg'
]

;(async function () {
  const res = await bestMaterialTemplateTree()
  bestMaterialTemplate.value = res.data.list
})()

const { platformList, getPlatformList } = usePlatform()
getPlatformList()
let editor135 = null
const onContentFrom135 = (event) => {
  if (typeof event.data !== 'string') {
    if (event.data.ready) {
      editor135.postMessage(JSON.parse(JSON.stringify(content.value)), '*')
    }
    return
  }

  if (event.data.indexOf('<') !== 0) return

  content.value = event.data
  window.removeEventListener('message', onContentFrom135)
}
const addCustomButtom = () => {
  window.UE.registerUI('upimg', (editor, uiName) => {
    // 注册按钮执行时的 command 命令，使用命令默认就会带有回退操作
    editor.registerCommand(uiName, {
      execCommand: function () {
        editor.execCommand('inserthtml', ``)
      }
    })
    // 创建一个 button
    const btn = new window.UE.ui.Button({
      // 按钮的名字
      name: uiName,
      // 提示
      title: '',
      // 需要添加的额外样式，可指定 icon 图标，图标路径参考常见问题 2
      cssRules:
        "background-image: url('https://images.maishou88.com/admin/buyer_circle_sc/20230922/20230922142338_7612.png') !important;background-size: 18px 18px",
      // 点击时执行的命令
      onclick: function () {
        imgvisible.value = true
      }
    })

    // 因为你是添加 button，所以需要返回这个 button
    return btn
  })
  window.UE.registerUI('upvideo', (editor, uiName) => {
    // 注册按钮执行时的 command 命令，使用命令默认就会带有回退操作
    editor.registerCommand(uiName, {
      execCommand: function () {
        editor.execCommand('inserthtml', ``)
      }
    })
    // 创建一个 button
    const btn = new window.UE.ui.Button({
      // 按钮的名字
      name: uiName,
      // 提示
      title: '',
      // 需要添加的额外样式，可指定 icon 图标，图标路径参考常见问题 2
      cssRules:
        "background-image: url('https://images.maishou88.com/admin/buyer_circle_sc/20230922/20230922140415_2386.png') !important;background-size: 16px 16px",
      // 点击时执行的命令
      onclick: function () {
        videovisible.value = true
      }
    })
    // 因为你是添加 button，所以需要返回这个 button
    return btn
  })
  window.UE.registerUI('goods', (editor, uiName) => {
    // 注册按钮执行时的 command 命令，使用命令默认就会带有回退操作
    editor.registerCommand(uiName, {
      execCommand: function () {
        editor.execCommand('inserthtml', ``)
      }
    })
    // 创建一个 button
    const btn = new window.UE.ui.Button({
      // 按钮的名字
      name: uiName,
      // 提示
      title: '',
      // 需要添加的额外样式，可指定 icon 图标，图标路径参考常见问题 2
      cssRules:
        "background-image: url('https://images.maishou88.com/admin/buyer_circle_sc/20230922/20230922120319_4716.png') !important;background-size: 22px 22px",
      // 点击时执行的命令
      onclick: function () {
        visible.value = true
      }
    })

    // 因为你是添加 button，所以需要返回这个 button
    return btn
  })
  window.UE.registerUI('editor', (editor, uiName) => {
    // 注册按钮执行时的 command 命令，使用命令默认就会带有回退操作
    editor.registerCommand(uiName, {
      execCommand: function () {
        editor.execCommand('inserthtml', ``)
      }
    })
    // 创建一个 button
    const btn = new window.UE.ui.Button({
      // 按钮的名字
      name: uiName,
      // 提示
      title: '',
      // 需要添加的额外样式，可指定 icon 图标，图标路径参考常见问题 2
      cssRules:
        "background-image: url('http://static.135editor.com/img/icons/editor-135-icon.png') !important;background-size: 20px 18px",
      // 点击时执行的命令
      onclick: function () {
        editor135 = window.open('https://www.135editor.com/simple_editor.html?callback=true&appkey=')
        window.removeEventListener('message', onContentFrom135)
        window.addEventListener('message', onContentFrom135, false)
      }
    })

    // 因为你是添加 button，所以需要返回这个 button
    return btn
  })

  window.UE.registerUI('xiumi-dialog', (editor, uiName) => {
    // 创建 “秀米弹窗”
    const dialog = new window.UE.ui.Dialog({
      // 注意：这是 xiumi-ue-dialog-v5.html 文件的访问链接，这个页面会通过 iframe 的方式嵌入到弹窗里
      iframeUrl: '/UEditor/' + 'xiumi/xiumi-ue-dialog-v5.html',
      editor,
      name: uiName,
      title: '秀米图文消息助手',
      cssRules: 'width: ' + (window.innerWidth - 60) + 'px; height: ' + (window.innerHeight - 60) + 'px;'
    })

    // 添加自定义按钮用于唤起“秀米弹窗”
    const btn = new window.UE.ui.Button({
      name: 'xiumi-connect',
      title: '秀米',
      cssRules: `background-image: url('https://xiumi.us/images/b80cd8.xiumi_logo_40.png') !important; background-size: 18px 18px;`,
      onclick() {
        dialog.render()
        dialog.open()
      }
    })

    return btn
  })
}

const goodsForm = ref({
  goodsStyle: '',
  sourceType: '',
  goodsId: '',
  activityId: ''
})
const couponForm = ref({
  sourceType: '',
  goodsCouponBg: '',
  opentype: 3,
  isturning: 1,
  itemsourceid: '',
  url: ''
})
const setGoodsForm = ref({
  goodsCouponDesc: '',
  goodsDesc: '',
  opentype: ''
})
const setGoodsVisible = ref(false)
const getGoodsLoading = ref(false)
const tableData = ref([])
const current = ref()
const columns = ref([
  {
    title: '商品名称',
    width: 150,
    dataIndex: 'title',
    tooltip: true,
    ellipsis: true
  },
  {
    title: '商品图',
    width: 90,
    slotName: 'picUrl'
  },
  {
    title: '券后价',
    dataIndex: 'actualPrice',
    width: 120
  },
  {
    title: '操作',
    width: 130,
    fixed: 'right',
    align: 'center',
    slotName: 'action'
  }
])
const openArr = [
  {
    title: '商品详情',
    id: 1
  },
  {
    title: '其他APP会场/领券',
    id: 3
  },
  {
    title: 'H5页面/买手妈妈APP会场',
    id: 2
  }
]
// 获取商品
const getGoods = () => {
  getGoodsLoading.value = true
  const { goodsId, sourceType, activityId, goodsStyle } = goodsForm.value
  const goodsIdArr = goodsId.split(',')
  let flag = 0
  goodsIdArr.forEach(async (item) => {
    goodsDetail2(
      deleteEmpty({
        goodsId: item,
        shopSearch: sourceType,
        activityId
      })
    )
      .then((res) => {
        const result = res.data
        result['goodsStyle'] = goodsStyle
        result['opentype'] = 1
        result['goodsCouponDesc'] = result['goodsDesc'] = ''
        tableData.value.push(result)
      })
      .catch(() => {
        Notification.error({
          title: '温馨提示',
          content: `商品ID：【${item}】获取失败`,
          closable: true,
          duration: 10000
        })
      })
      .finally(() => {
        flag++
        if (flag === goodsIdArr.length) {
          getGoodsLoading.value = false
        }
      })
  })
}
// 导入商品
const onImportGoods = async (option) => {
  try {
    importLoading.value = true
    const { fileItem } = option
    const formData = new FormData()
    formData.append('file', fileItem.file)
    const res = await bestMaterialImportForList(formData)
    if (res?.data?.length) {
      goodsForm.value.goodsId = res.data.join(',')
      getGoods()
    }
  } finally {
    importLoading.value = false
  }
}
// 删除商品
const onDeleteItem = (index) => {
  tableData.value.splice(index, 1)
}
// 打开商品设置框
const openSetGoods = (index) => {
  current.value = index
  const { opentype, goodsCouponDesc, goodsDesc } = tableData.value[index]
  setGoodsForm.value.opentype = opentype
  setGoodsForm.value.goodsCouponDesc = goodsCouponDesc
  setGoodsForm.value.goodsDesc = goodsDesc
  setGoodsVisible.value = true
}
// 确认设置商品
const setGoods = () => {
  const { opentype, goodsCouponDesc, goodsDesc } = setGoodsForm.value
  tableData.value[current.value].opentype = opentype
  tableData.value[current.value].goodsCouponDesc = goodsCouponDesc
  tableData.value[current.value].goodsDesc = goodsDesc
}
const onOk = () => {
  let tempGoodsStyle = ''
  switch (type.value) {
    // 商品
    case 'goods': {
      tableData.value.forEach((el) => {
        let tempGoodsStyleCopy = el.goodsStyle
          .replace('{{data-showtype}}', el.shopType)
          .replace('{{data-opentype}}', el.opentype)
          .replace('{{data-itemsource}}', el.sourceType)
          .replace('{{data-itemsourceid}}', el.goodsId)
          .replace('{{goodsImg}}', el.picUrl)
          .replace('{{goodsTitle}}', el.title)
          .replace('{{goodsCouponPrice}}', el.couponPrice)
          .replace('{{goodsCouponDesc}}', el.goodsCouponDesc)
          .replace('{{goodsDesc}}', el.goodsDesc)
          .replace('{{goodsActualPrice}}', el.actualPrice)
          .replace('{{goodsOriginalPrice}}', el.originalPrice)
          .replace('{{goodsShopLogo}}', el.shopLogo)
        if (el.couponPrice && el.couponPrice > 0) {
          tempGoodsStyleCopy = tempGoodsStyleCopy.replace('<!--', '').replace('-->', '')
        }
        tempGoodsStyle = tempGoodsStyle + tempGoodsStyleCopy
      })
      const myEditor = window.UE.getEditor(id)
      myEditor.execCommand('inserthtml', tempGoodsStyle)
      goodsForm.value.goodsStyle =
        goodsForm.value.sourceType =
        goodsForm.value.goodsId =
        goodsForm.value.activityId =
          ''
      tableData.value = []
      break
    }

    case 'coupon': {
      const couponStyle =
        '<span style="display:inline-block" data-showtype="{{data-showtype}}" data-isturning="{{data-isturning}}" data-opentype="{{data-opentype}}" data-itemsource="{{data-itemsource}}" data-itemsourceid="{{data-itemsourceid}}" data-linktext="{{data-linktext}}" data-splicepid="{{data-splicepid}}" data-url="{{data-url}}" data-extendjson="{{data-extendjson}}" data-suppliercode="{{data-suppliercode}}" style="vertical-align:inherit;color: rgb(102, 102, 102);"><img src="{{goodsCouponBg}}" style="max-width: 100% !important;box-sizing:border-box;vertical-align: inherit; width: 100%;" /></span>'
      if (couponForm.value.url.indexOf('msmm://appView?path=') != -1) {
        couponForm.value.url = couponForm.value.url.replace('msmm://appView?path=', '')
      }
      const opentype = couponForm.value.opentype == 4 ? 3 : couponForm.value.opentype
      tempGoodsStyle = couponStyle
        .replace('{{data-opentype}}', opentype)
        .replace('{{data-itemsource}}', couponForm.value.sourceType)
        .replace('{{data-itemsourceid}}', couponForm.value.itemsourceid)
        .replace('{{data-url}}', couponForm.value.url)
        .replace('{{data-suppliercode}}', couponForm.value.suppliercode)
        .replace('{{data-isturning}}', couponForm.value.isturning)
        .replace('{{goodsCouponBg}}', couponForm.value.goodsCouponBg)
      const myEditor = window.UE.getEditor(id)
      myEditor.execCommand('inserthtml', tempGoodsStyle)
      couponForm.value.sourceType =
        couponForm.value.goodsCouponBg =
        couponForm.value.itemsourceid =
        couponForm.value.url =
          ''
      couponForm.value.opentype = 3
      couponForm.value.isturning = 1
      break
    }
  }
  return true
}

const initContent = computed(() => {
  return props.modelValue
})

watch(
  initContent,
  (newVal) => {
    content.value = newVal
  },
  { deep: true, immediate: true }
)

watch(
  content,
  (newVal) => {
    emit('input', newVal)
  },
  { deep: true }
)

defineExpose({ setHeightFun })
</script>
<style scoped lang="scss">
:deep(#edui1) {
  height: 100%;
}
</style>
